package com.sihan.swvp.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Vector;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


public class XssFilter implements Filter {

		private MultipartResolver multipartResolver = null;
		
		@Override  
		public void init(FilterConfig fc) throws ServletException {  
			
		}  
		@Override
		public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
				throws IOException, ServletException {
			XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) getRequest(request));
			filterChain.doFilter(xssRequest, response);
			
		}

		@Override
		public void destroy() {
			// TODO Auto-generated method stub
			
		}
		

		/** 
		 * 获取 request 
		 * @param req 
		 * @return 
		 */  
		private ServletRequest getRequest(ServletRequest req){  
		    String enctype = req.getContentType();
		    String apptype = "";
		    if(enctype != null){
		    	apptype = enctype.split(";")[0];
		    }
		    if (StringUtils.isNotBlank(apptype) && apptype.contains("multipart/form-data"))  {
		        // 返回 MultipartHttpServletRequest 用于获取 multipart/form-data 方式提交的请求中 上传的参数
		    	multipartResolver = new CommonsMultipartResolver(((HttpServletRequest) req).getSession().getServletContext());
		    	MultipartHttpServletRequest multipartRequest = multipartResolver.resolveMultipart((HttpServletRequest) req);
		        return multipartRequest;  
		    }
		    else   
		        return req;  
		}  
	
}
